import React from 'react';
import { Link } from 'react-router-dom';
import { Menu, Icon } from 'antd';
import menus from '../menus';

const SubMenu = Menu.SubMenu;

class FrameMenus extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { name } = this.findDefaultKey(menus);
    this.setActiveName(name);
  }

  setActiveName = (name) => {
    let { setName } = this.props;
    if (setName) {
      setName(name);
    }
  };

  renderMenus = (menus) => {
    return menus.map((item) => {
      // 有子菜单
      if (item.children) {
        return (
          <SubMenu
            key={ item.name }
            title={ <span><Icon type={ item.icon } /><span>{ item.name }</span></span> }
          >
            { this.renderMenus(item.children) }
          </SubMenu>
        );
      }
      // 没有子菜单
      return (
        <Menu.Item key={ item.path }>
          { item.path ?
            <Link onClick={() => this.setActiveName(item.name)} to={ item.path }>
              <Icon type={ item.icon } /> { item.name }
              </Link> :
            <span onClick={() => this.setActiveName(item.name)}><Icon type={ item.icon } /> { item.name }</span> }
        </Menu.Item>
      );
    });
  };

  findDefaultKey = (menus) => {
    let key = '';
    let name = '';
    for (let i = 0; i < menus.length; i++) {
      const item = menus[i];
      if (item.path) {
        key = item.path;
        name = item.name;
        break;
      }
      if (item.children) {
        const data = this.findDefaultKey(item.children);
        key = data.key;
        name = data.name;
        break;
      }
    }
    return { key, name };
  };

  render() {
    let { key = '' } = this.findDefaultKey(menus);
    return (
      <Menu
        theme='dark'
        defaultSelectedKeys={ [key] }
        mode='inline'
      >
        { this.renderMenus(menus, 0) }
      </Menu>
    );
  }
}

export default FrameMenus;